<?php
/**
 * @file $HeadURL: imagecategory.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2015-1-5 下午12:11:13 $
 * @brief 
 */
namespace haibao\cms\data;


class ImageCategory extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImageCategory');
	}
	
	/**
	 * 添加新的图片与图片分类的关联关系
	 * @param int $imageId
	 * @param array $categoryIds
	 */
	public function addImageCategorys($imageIds, $categoryIds){
		if(!$categoryIds){
			return false;
		}
		$this->beginTranscation();
		try {
			$imageIds = (array)$imageIds;
			$categoryIds = (array)$categoryIds;
			$str = preg_replace('/(\d+)/', '%s', implode(',', $categoryIds));
			
			// 删除旧的关联关系
			$this->deleteImageCategorys($imageIds);
			
			//添加新的关联关系
			$sql = 'insert into ImageCategory(ImageId, CategoryId, Display) values ';
			$arrSql = $arrValues = array();
			
			foreach($imageIds as $imageId){
				foreach ($categoryIds as $category){
					array_push($arrSql, '(%s,%s,%s)');
					array_push($arrValues, $imageId);
					array_push($arrValues, $category);
					array_push($arrValues, \haibao\cms\model\data\ImageCategory::DISPLAY_ENABLE);
				}
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 删除旧的图片和分类的关联关系
	 * @param array $imageIds
	 */
	public function deleteImageCategorys($imageIds){
		if(!$imageIds){
			return false;
		}
		$imageIds = (array)$imageIds;
		$imageIdStr = implode(',', $imageIds);
		$str = preg_replace('/(\d+)/', '%s', $imageIdStr);
		
		$sql = "delete from ImageCategory where ImageId in ({$str})";
		$this->query($sql, $imageIds);
	}
}